import Vue from 'vue';
import iView from 'iview';
import Util from '../libs/util';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import {routers, otherRouter, appRouter} from './router';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
    // mode: 'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);
import {exam} from '../../api/index.js';
router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);

    if(to.path.indexOf("/portal")>=0){
        Util.toDefaultPage([...routers], to.name, router, next);
    }else if (to.name==='login'){
        Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);
    }else{
        exam.checkLogin_post().then((res)=> {
            if(res.data.resCode!=0){
                next({
                     name: 'login'
                 });
            }else{
                Util.title();
                let email = res.data.data.user.email;
                let status = res.data.data.user.userStatus;

                if(status==0){
                    next({
                        name: 'portal_regist',
                        params: { email: email,status:status }
                    });
                }else if(status==1){
                    next({
                        name: 'portal_regist',
                        params: { email: email,status:status,student:res.data.data.student }
                    });
                }
                else if(status==2){
                    Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);
                }
                //Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);
            }
        }, function (error) {
            alert("系统异常，请先联系管理员");
        });
        // if (!Cookies.get('user') && to.name !== 'login') {  // 判断是否已经登录且前往的页面不是登录页
        //     next({
        //         name: 'login'
        //     });
        // } else if (Cookies.get('user') && to.name === 'login') {  // 判断是否已经登录且前往的是登录页
        //     Util.title();
        //     next({
        //         name: 'home_index'
        //     });
        // } else {
        //      Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next);
        // }




    }
});

router.afterEach((to) => {
    Util.openNewPage(router.app, to.name, to.params, to.query);
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});
